package com.dongdongshop.serviceimpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.FreemarkerService;
import com.dongdongshop.service.TbGoodsDescService;
import com.dongdongshop.service.TbGoodsService;
import com.dongdongshop.service.TbItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@org.springframework.stereotype.Service
public class FreemarkerServiceImpl implements FreemarkerService {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Reference
    private TbGoodsService tbGoodsService;
    @Reference
    private TbGoodsDescService tbGoodsDescService;
    @Reference
    private TbItemService tbItemService;
    @Override
    public void createPage (String[] goodsids){
        for (int i = 0; i < goodsids.length; i++) {
            createPage2(Long.parseLong(goodsids[i]));
        }
    }
    public void createPage2(Long goodsid) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter writer = null;
        try {
            //        第四步：加载一个模板，创建一个模板对象。
            Template template = configuration.getTemplate("item.ftl");
            //        第五步：创建一个模板使用的数据集，可以是 pojo 也可以是 map。一般是 Map。
            Map map = new HashMap();
            //        第六步：创建一个 Writer 对象，一般创建一 FileWriter 对象，指定生成的文件名。
            writer = new FileWriter("D:\\freemarker\\" + goodsid + ".html");


            //数据填充
            //根据id查询当前商品
            TbGoods tbGoods = tbGoodsService.selectGoodsById(goodsid);
            //根据goodsid查询商品详情信息
            TbGoodsDesc tbGoodsDesc = tbGoodsDescService.selectGoodsDescByGoodsId(goodsid);
            //根据goodsid查询item数据
            List<TbItem> tbItemList = tbItemService.selectItemByGoodsId(goodsid);
            map.put("goods",tbGoods);
            map.put("tbGoodsDesc",tbGoodsDesc);
            map.put("tbItemList",tbItemList);
//        第七步：调用模板对象的 process 方法输出文件。
            template.process(map,writer);

        } catch (Exception e) {
             e.printStackTrace();
        }finally {
            try {
                //        第八步：关闭流
                if (writer != null){
                    writer.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }


    }
}
